<template>
    <div id="app">
        <el-container style="background: url(http://rww08uahf.hn-bkt.clouddn.com/0dd8ed5b730c4df7babec5898c4b641c.png);">
            <el-header>

                <Top/>
            </el-header>
            <el-main class="center">
                <el-row gutter="20">

                    <el-col span="24">
                        <el-card style="background-color: rgba(255,255,255,90%)">
                            <!--标签页卡开始-->
                            <el-page-header @back="goBack" content="发布">
                            </el-page-header>

                            <el-divider></el-divider>
                            <!--标签页卡结束-->
                            <!--发布文章表单开始-->
                            <el-form label-width="100px">
                                <el-form-item label="文章标题">
                                    <el-input style="width: 800px" v-model="c.blogTitle" placeholder="请输入标题"></el-input>
                                </el-form-item>
                                <el-form-item label="文章分类">
                                    <el-select v-model="c.blogTypeId">
                                        <el-option v-for="cat in categoryArr" :label="cat.modelName" :value="cat.id"></el-option>
                                    </el-select>
                                </el-form-item>
                                <div class="upload_icon">
                                    <el-form-item label="上传：" prop="addForm">
                                        <el-upload
                                            :auto-upload="false"
                                            :limit="limitCount"
                                            :on-remove="handleRemove"
                                            :on-change="onChange"
                                            :on-success="handleSuccess"
                                            :file-list="fileList"
                                            :before-upload="beforeAvatarUpload"
                                            action="#"
                                            name='file'
                                            class="avatar-uploader"
                                            list-type="picture-card"
                                            accept="image/jpg,image/jpeg,image/png">
                                            <img v-if="url" :src="url" class="el-upload-list__item-thumbnail"></img>
                                            <i v-else slot="default" class="el-icon-plus" />
                                        </el-upload>
                                        <div class="el-upload__tip">"png",  "jpg", "jpeg"格式，大小5M以内</div>
                                    </el-form-item>
                                </div>
                                <el-form-item  label="文章内容">
                                    <mavon-editor v-model="c.blogContent" ref="md" :toolbars="toolbars" @imgAdd="imgAdd" @imgDel="imgDel"/>

                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="put()" style="margin-left: 10%;width: 80%">发布</el-button>
                                </el-form-item>
                            </el-form>
                            <!--发布文章表单结束-->
                        </el-card>
                    </el-col>
                </el-row>
            </el-main>
            <Bottom/>
        </el-container>
    </div>
</template>
<script>
import Top from "@/components/Top.vue";
import Bottom from "@/components/Bottom.vue";
require('./edit/js/index.min.js');
import axios from "axios";
import '@/api/request'

export default {
    components: {Top,
        Bottom,},
    data() {
        return {

            context: ' ',//输入的数据,
            limitCount: 1,
            addOrderVisible: false,
            toolbars: {
                bold: true, // 粗体
                italic: true, // 斜体
                header: true, // 标题
                underline: true, // 下划线
                mark: true, // 标记
                superscript: true, // 上角标
                quote: true, // 引用
                ol: true, // 有序列表
                link: true, // 链接
                imagelink: true, // 图片链接
                help: true, // 帮助
                code: true, // code
                subfield: true, // 是否需要分栏
                fullscreen: true, // 全屏编辑
                readmodel: true, // 沉浸式阅读
                /* 1.3.5 */
                undo: true, // 上一步
                trash: true, // 清空
                save: true, // 保存（触发events中的save事件）
                /* 1.4.2 */
                navigation: true // 导航目录
            },
            onChangeImgUrl: '',
            fileList: [],
            dialogVisible: false,
            categoryArr: [],
            c: {
                blogTitle: "", blogImg: "", blogContent: "", blogTypeId: ""
            },

        }
    },watch: {
        onChangeImgUrl: {
            handler(newName) {
                var aa = document.querySelector('.el-upload--picture-card')
                if (newName) {
                    aa.style.display = 'none'
                } else {
                    setTimeout(() => {
                        aa.style.display = 'inline-block'
                    }, 1100)
                }
            }
        }
    },

    methods: {
        goBack() {
            window.location.href="index.html"
        },
        put(){
            console.log(this.c.blogImg)
            axios.post('http://localhost:8088/blog/publish',this.c).then((response) => {
                if (response.data.code==1){
                    this.$message("发布成功")
                    window.location.href="index.html"
                }else {
                    this.$message(response.data.msg)
                }
            });
        },
        imgDel(pos){
            //上面讲过图片是一个数组，那么这里直接通过pos[0]取出文件路径。
            let url = pos[0]
            /*调用axios发送请求。此处自己自行创建了一个header键值进行数据传递*/
            axios({
                url:'http://localhost:8088/qiniu/imgDel',
                method:'POST',
                headers:{'Img-Delete': url},
            }).then().catch(error=>{this.$message({message:error,type:'error',showClose:true,center:true})})
        },
        //script部分
        imgAdd(pos,file){
            //这里的pos指的是在数组中的下标
            //这里创建FormData对象并将从本地获取到的file值存入。
            var formdata = new FormData();
            formdata.append('file', file)
            /*
              调用axios请求。这里我原先的做法：使用封装好的api，此处直接调用方法名，但是一直报400 (bad request)错误
              可能是受axios配置文件中的request拦截器的某些影响(看了挺久代码还是没看出来哪里有问题)
              所以这里就直接引入axios进行请求发送了
            */
            axios({
                //后端有 spring.mvc.servlet.path:/api 配置，以便后续nginx控制
                url: 'http://localhost:8088/qiniu/uploadImg',
                method: 'post',
                data: formdata,
                headers: { 'Content-Type': 'multipart/form-data' }, //这一步不能丢
            }).then(url=>{
                //在<mavon-editor ref="md">标签中使用ref进行引用，这里使用$refs.md进行获取Editor对象
                this.$refs.md.$img2Url(pos, url.data.data)
            }).catch(error=>{this.$message({message: error, type: 'error', showClose: true,center:true})})
        },
        onChange(file) {
            console.log(file)
            // debugger
            let formData = new FormData();
            formData.append("file", file.raw);
            axios.post('http://localhost:8088/qiniu/uploadImg',formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
            }).then((res) =>{
                if (res.data.code==1){
                    this.$message('上传成功')
                    this.onChangeImgUrl = res.data.data
                    this.c.blogImg=this.onChangeImgUrl
                }else {
                    this.$message(res.data.msg)
                }
            });
        },
        handleRemove(file, fileList) {
            this.onChangeImgUrl = ''
        },
        handleSuccess(res, file) {
            this.onChangeImgUrl=res.data
        },
        // 限制图片大小
        beforeAvatarUpload(file) {
            const isLt5M = file.size / 1024 / 1024 < 5
            if (!isLt5M) {
                this.$message.error('上传头像图片大小不能超过 5MB!')
            }
            return isLt5M
        }

    },
    created: function () {
        //请求文章类型下的所有分类
        axios.get('http://localhost:8088/blogType/list').then((response) => {
            if (response.data.code == 1) {
                this.categoryArr = response.data.data;
            }else {
                this.$message('查询失败');
            }
        })
    }
}

</script>

<style>
@import url(//at.alicdn.com/t/c/font_4004562_b46lfqtm52u.css);
body {
    margin: 0;
    overflow-y: scroll;
    overflow-x: hidden;
    /* 背景渐变 */
    background: linear-gradient(90deg, rgba(247, 149, 51, .1), rgba(243, 112, 85, .1) 15%, rgba(239, 78, 123, .1) 30%, rgba(161, 102, 171, .1) 44%, rgba(80, 115, 184, .1) 58%, rgba(16, 152, 173, .1) 72%, rgba(7, 179, 155, .1) 86%, rgba(109, 186, 130, .1));
}
.shadow {
    box-shadow: 0 4px 8px 6px rgba(7, 17, 27, .06);
}

::-webkit-scrollbar {
    /*滚动条整体样式*/
    width : 4px;  /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
}
::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius   : 10px;
    background-color: #1d2d44;
    background-image: -webkit-linear-gradient(
        45deg,
        rgba(255, 255, 255, 0.2) 25%,
        transparent 25%,
        transparent 50%,
        rgba(255, 255, 255, 0.2) 50%,
        rgba(255, 255, 255, 0.2) 75%,
        transparent 75%,
        transparent
    );
}
::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow   : inset 0 0 5px rgba(0, 0, 0, 0.2);
    background   : #ededed;
    border-radius: 10px;
}



.center {
    width: 100%;
    margin: 0 auto;
    min-width: 1200px;
}

#footer_center p {
    margin: 0;
}

#footer_center h3 {
    color: white;
}

.el-message {
    top: 100px !important;
}

.el-header {
    background-color: white;
    padding: 20px 0
}
</style>